/*
 * #depends subsonic-application.js
 */
Ext.regController('Ext.ux.mattgoldspink.subsonic.controllers.User', {
        login: function(){
            Ext.regModel('Ext.ux.mattgoldspink.subsonic.model.User', {
                fields: ['u', 'p'],
                proxy: {
                    id: 'Ext.ux.mattgoldspink.subsonic.model.User',
                    type: 'localstorage'
                }
            });
            //our Store automatically picks up the LocalStorageProxy defined on the Search model
            this.store = new Ext.data.Store({
                model: "Ext.ux.mattgoldspink.subsonic.model.User"
            });

            //loads any existing Search data from localStorage
            this.store.load({
                scope   : this,
                callback: function(records){
                    if (records.length === 0) {
                        this.loginForm =this.makeLoginForm();
                        this.loginForm.show('pop');
                    } else {
                        Ext.apply(Ext.ux.mattgoldspink.subsonic.LoginDetails, records[0].data);
                        this.doAfterLogin();
                    }
                }
            });
        },
        doAfterLogin: function(){
            Ext.dispatch({
                controller: 'Ext.ux.mattgoldspink.subsonic.controllers.MusicStore',
                action: 'initialise'
            });
        },
        makeLoginForm: function(){
            return new Ext.Panel({
                floating: true,
                modal: true,
                centered: true,
                hideMaskOnTap: true,
                dockedItems: [
                    {
                        title: 'Login',
                        xtype: 'toolbar',
                        dock: 'top'   
                    }
                ],   
                items: [
                    {
                        xtype: 'form',
                        items: [
                            {
                                xtype: 'fieldset',
                                instructions: 'Please enter the information above.',
                                defaults: {
                                    // labelAlign: 'right'
                                    labelWidth: '35%'
                                },
                                items: [
                                    {
                                        xtype: 'textfield',
                                        name: 'u',
                                        label: 'Username',
                                        placeHolder: 'username',
                                        required: true,
                                        useClearIcon: true
                                    }, {
                                        xtype: 'passwordfield',
                                        name: 'p',
                                        label: 'Password',
                                        required: true,
                                        useClearIcon: true
                                    }
                                ]
                            },
                            {
                                xtype: 'fieldset',
                                items: [
                                    {
                                        xtype: 'button',
                                        text: 'Login',
                                        scope: this,
                                        handler: this.doLogin
                                    }
                                ]
                            }
                        ]
                    }
                ]
            });
        },
        doLogin: function(button){
            var form = button.ownerCt.ownerCt,
            values = form.getValues(),
            username = values.u,
            password = values.p;
            this.loginForm.hide('pop');
            Ext.Msg.show({
                   msg: 'Verifying your username and password',
                   width: 300
            });
            var params = {
                'u': username,
                'p': 'enc:'+Ext.ux.mattgoldspink.subsonic.hexEncode(password)
            };
            Ext.apply(params, Ext.ux.mattgoldspink.subsonic.LoginDetails);
            Ext.Ajax.request({
               url: Ext.ux.mattgoldspink.subsonic.apiUrl + '/rest/ping.view',
               scope: this,
               success: function(response) {
                   response = Ext.decode(response.responseText);
                    var status = response['subsonic-response'].status;
                    if (status === 'ok') {
                        this.store.add({u: params.u, p: params.p});
                        this.store.sync();
                        Ext.apply(Ext.ux.mattgoldspink.subsonic.LoginDetails, {u: params.u, p: params.p});
                        this.loginForm.destroy();
						Ext.dispatch({
							controller: 'Ext.ux.mattgoldspink.subsonic.controllers.MusicStore',
							action: 'initialise'
						});
                    } else {
                        Ext.Msg.hide();
                        Ext.Msg.setIcon(Ext.MessageBox.ERROR);
                        Ext.Msg.alert('Error', 'There was an error logging please check your credentials: <br/>' + response.responseText,
                        function(){
                            this.loginForm.show('pop');
                            form.reset(); 
                        });
                    }                            
               },
               failure: function(){
                    this.login();
               },
               params: params
           });
        }
    });
